package com.zhu.shopcenter.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhu.commons.utils.JwtInfo;
import com.zhu.commons.utils.JwtUtils;
import com.zhu.commons.utils.R;
import com.zhu.shopcenter.pojo.TradeOrder;
import com.zhu.shopcenter.service.ITradeOrderService;
import com.zhu.shopcenter.service.PayService;

import com.zhu.shopcenter.zhifubao.AlipayBean;
import com.zhu.shopcenter.zhifubao.Properties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@RestController
@RequestMapping("api/auth/order")
@Api(tags = "支付宝支付模块")
@Slf4j
public class PayController {
    @Autowired
    private ITradeOrderService orderService;
    @Autowired
    private Properties properties;
    @Autowired
    private PayService payService;

    @GetMapping("/pay/{orderId}")
    @ApiOperation(value = "支付接口")
    public String alipay(@PathVariable String orderId) throws AlipayApiException, IOException {
        String pay = payService.pay(orderId);
        return pay;
    }

    @GetMapping("/paytest/{orderId}")
    @ApiOperation(value = "支付接口")
    public R apy(@PathVariable String orderId) throws AlipayApiException, IOException {
        String pay = payService.pay(orderId);
        return R.ok().data("body", pay);
    }


    @GetMapping("notify")
    @ApiOperation(value = "支付宝成功回调")
    public String notify(HttpServletRequest request) throws AlipayApiException {
        // 这里首先验签 验证是支付宝发来的请求
        HashMap<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, properties.getPublicKey(), "utf-8", "RSA2");
        log.info("支付：",signVerified);
        if (signVerified) {
            /**
             * 改变账单状态为已支付
             *
             */
            String out_trade_no = request.getParameter("out_trade_no");
            LambdaQueryWrapper<TradeOrder> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TradeOrder::getOrderNo, out_trade_no);
            TradeOrder order = orderService.getOne(queryWrapper);
            order.setStatus(1);
            orderService.updateById(order);
            log.info("账单号：{}", out_trade_no);
            // 收到支付宝异步通知,返回success,支付宝不再通知
            log.info("收到支付宝通知: {}", signVerified);
            //保存交易流水  返回success
            log.info("支付成功！");
            return "success";
        }
        return "success";
    }
}




//    @Autowired
//    private Properties properties;
//    @RequestMapping(value = "/paying/{courseId}",method = RequestMethod.GET)
//    @ResponseBody
//    public String pay(@PathVariable String courseId) throws AlipayApiException {
//        //模拟数据
//        TradeOrder order = orderService.getById(courseId);
//        AlipayBean alipayBean=new AlipayBean();
//        alipayBean.setOut_trade_no(order.getOrderNo());
//        alipayBean.setSubject(order.getCourseTitle());
//        alipayBean.setTotal_amount(String.valueOf(new Random().nextInt(100)));
//        alipayBean.setBody("商品描述");
//
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                properties.getBaseUrl(),
//                properties.getAppId(),
//                properties.getSecurityKey(),
//                "json",
//                "utf-8",
//                properties.getSecurityKey(),
//                "RSA2");
//        //PC网页支付使用AlipayTradePagePayRequest传参，下面调用的是pageExecute方法
//        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
////        alipayRequest.setReturnUrl();
////        alipayRequest.setNotifyUrl(notifyUrl);
//        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
//        log.info("封装请求支付宝付款参数为:{}", JSON.toJSONString(alipayRequest));
//        // 调用SDK生成表单
//        String result = alipayClient.pageExecute(alipayRequest).getBody();
//        log.info("请求支付宝付款返回参数为:{}", result);
//        return result;
//    }

